// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: "test4-ht5oe"
})
const db = cloud.database()
const cartsdb = db.collection('CartsData')
const _ = db.command
var $ = db.command.aggregate

// 云函数入口函数
exports.main = async (event, context) => {
  console.log(event.userid)
  const Tuinadata =await cartsdb.aggregate()
  .match({
    UserID: event.userid,
    className:'tuina'
  })
  .lookup({
    from: 'TuinaData',
    localField: 'CartsID',
    foreignField: 'TuinaID',
    as: 'cartsInfo',
  }).replaceRoot({
    newRoot: $.mergeObjects([ $.arrayElemAt(['$cartsInfo', 0]), '$$ROOT' ])
  }).match({
    TuinaID: _.exists(true)
  })
  .project({
    cartsInfo:0,
    TuinaDetailIntro:0
  })
  .end()

  const Meddata = await cartsdb.aggregate()
  .match({
    UserID: event.userid,
    className:'medic'
  })
  .lookup({
    from: 'MedicineData',
    localField: 'CartsID',
    foreignField: 'MedicID',
    as: 'cartsInfo',
  }).replaceRoot({
    newRoot: $.mergeObjects([ $.arrayElemAt(['$cartsInfo', 0]), '$$ROOT' ])
  }).match({
    MedicID: _.exists(true)
  })
  .project({
    cartsInfo:0,
    MedicDetailIntro:0
  })
  .end()

  const Sidedata = await cartsdb.aggregate()
  .match({
    UserID: event.userid,
    className:'sideline'
    })
  .lookup({
    from: 'SidelineData',
    localField: 'CartsID',
    foreignField: 'SidelineID',
    as: 'cartsInfo',
  }).replaceRoot({
    newRoot: $.mergeObjects([ $.arrayElemAt(['$cartsInfo', 0]), '$$ROOT' ])
  }).match({
    SidelineID: _.exists(true)
  })
  .project({
    cartsInfo:0,
    SidelineDetailIntro:0
  })
  .end()
  
  return { 
Tuinadata,Meddata,Sidedata
   }
}